#include "node-manager.h"
#include "ns3/log.h"
#include "ns3/constant-position-mobility-model.h"
#include "ns3/mobility-helper.h"
#include "ns3/position-allocator.h"
#include "ns3/waypoint-mobility-model.h"
#include "ns3/udp-echo-helper.h"
#include "ns3/ipv4-address-helper.h"
#include "ns3/internet-stack-helper.h"
#include "ns3/uinteger.h"

#include <fstream>
#include <sstream>
#include <algorithm>
#include <cmath>
#include <dirent.h>
#include <string>
#include <regex>

namespace ns3 {

// 添加日志组件注册，这是关键修复
NS_LOG_COMPONENT_DEFINE("NodeManager");

NodeManager::NodeManager() 
    : m_groundStationCoverageRadius(1000.0),
      m_satelliteMaxElevationAngle(45.0)
{
    NS_LOG_FUNCTION(this);
}

NodeManager::~NodeManager() {
    NS_LOG_FUNCTION(this);
}

void NodeManager::LoadVehicles(const std::string& dirPath) {
    NS_LOG_FUNCTION(this << dirPath);
    
    // 清空之前的数据
    m_vehicleTrajectories.clear();
    
    // 获取目录下所有vehicle_*.csv文件
    DIR* dir;
    struct dirent* ent;
    std::regex vehicleFilePattern("vehicle_(\\d+)\\.csv");
    std::smatch matches;
    
    if ((dir = opendir(dirPath.c_str())) != NULL) {
        while ((ent = readdir(dir)) != NULL) {
            std::string filename = ent->d_name;
            if (std::regex_match(filename, matches, vehicleFilePattern)) {
                std::string vehicleId = matches[1].str();
                std::string filePath = dirPath + "/" + filename;
                
                // 解析车辆轨迹文件
                std::vector<VehicleData> trajectory = ParseVehicleCSV(filePath, vehicleId);
                
                if (!trajectory.empty()) {
                    m_vehicleTrajectories[vehicleId] = trajectory;
                    NS_LOG_INFO("Loaded trajectory for vehicle " << vehicleId << " with " 
                               << trajectory.size() << " waypoints");
                }
            }
        }
        closedir(dir);
    } else {
        NS_LOG_ERROR("Could not open directory: " << dirPath);
        return;
    }
    
    NS_LOG_INFO("Loaded trajectories for " << m_vehicleTrajectories.size() << " vehicles");
    
    // 添加日志，显示找到了多少车辆文件
    NS_LOG_INFO("Found " << m_vehicleTrajectories.size() << " vehicle files in directory: " << dirPath);
    
    // 对每个车辆文件处理...
    for (const auto& [vehicleId, trajectory] : m_vehicleTrajectories) {
        // 添加日志，显示加载了多少车辆数据
        NS_LOG_INFO("Loaded " << trajectory.size() << " data entries for vehicle " << vehicleId);
    }
    
    // 如果没有加载任何车辆数据，输出警告
    if (m_vehicleTrajectories.empty()) {
        NS_LOG_WARN("No vehicle data was loaded! Check the path: " << dirPath);
    }
}

void NodeManager::LoadSatellites(const std::string& filePath) {
    NS_LOG_FUNCTION(this << filePath);
    m_satellitePositions = ParsePositionCSV(filePath);
    NS_LOG_INFO("Loaded " << m_satellitePositions.size() << " satellite positions");
}

void NodeManager::LoadGroundStations(const std::string& filePath) {
    NS_LOG_FUNCTION(this << filePath);
    m_groundStationPositions = ParsePositionCSV(filePath);
    NS_LOG_INFO("Loaded " << m_groundStationPositions.size() << " ground station positions");
}

std::vector<VehicleData> NodeManager::ParseVehicleCSV(const std::string& filePath, const std::string& vehicleId) {
    std::vector<VehicleData> data;
    std::ifstream file(filePath);
    
    if (!file.is_open()) {
        NS_LOG_ERROR("Failed to open file: " << filePath);
        return data;
    }
    
    std::string line;
    // 跳过标题行
    std::getline(file, line);
    
    while (std::getline(file, line)) {
        std::stringstream ss(line);
        std::string token;
        VehicleData vehicle;
        
        // 解析CSV行 (new_vehicle_id,x,y,z,time,speed)
        std::getline(ss, token, ',');  // new_vehicle_id
        vehicle.id = vehicleId;  // 使用文件名中的ID，而不是CSV中的ID
        
        std::getline(ss, token, ',');  // x
        vehicle.x = std::stod(token);
        
        std::getline(ss, token, ',');  // y
        vehicle.y = std::stod(token);
        
        std::getline(ss, token, ',');  // z
        // 忽略z值，但在大多数车辆仿真中不使用
        // 修改：移除未使用的变量z以避免编译警告
        std::stod(token);
        
        std::getline(ss, token, ',');  // time
        vehicle.time = std::stod(token);
        
        std::getline(ss, token, ',');  // speed
        vehicle.speed = std::stod(token);
        
        // 计算角度 (可选，如果需要的话)
        vehicle.angle = 0.0;  // 默认设为0，如果需要可以根据前后点计算
        
        data.push_back(vehicle);
    }
    
    // 按时间排序轨迹点
    std::sort(data.begin(), data.end(), 
              [](const VehicleData& a, const VehicleData& b) {
                  return a.time < b.time;
              });
    
    return data;
}

std::vector<PositionData> NodeManager::ParsePositionCSV(const std::string& filePath)
{
    NS_LOG_FUNCTION(this << filePath);
    
    std::vector<PositionData> positions;
    std::ifstream file(filePath);
    
    if (!file.is_open()) {
        std::cerr << "Failed to open file: " << filePath << std::endl;
        return positions;
    }
    
    std::string line;
    bool firstLine = true;
    int id = 0;
    
    while (std::getline(file, line)) {
        // 跳过CSV头部和注释行
        if (firstLine || line.empty() || line[0] == '#' || line.find("//") == 0) {
            firstLine = false;
            continue;
        }
        
        std::stringstream ss(line);
        std::string cell;
        std::vector<std::string> cells;
        
        while (std::getline(ss, cell, ',')) {
            cells.push_back(cell);
        }
        
        if (cells.size() >= 3) {
            PositionData data;
            data.id = std::to_string(id++);
            
            try {
                data.x = std::stod(cells[0]);
                data.y = std::stod(cells[1]);
                data.z = std::stod(cells[2]);
                
                // 输出调试信息
                NS_LOG_DEBUG("CSV解析 - 位置数据: id=" << data.id 
                           << ", x=" << data.x << ", y=" << data.y << ", z=" << data.z);
                
                positions.push_back(data);
            } catch (const std::exception& e) {
                std::cerr << "Error parsing position data: " << e.what() << std::endl;
            }
        }
    }
    
    file.close();
    
    if (positions.empty()) {
        std::cerr << "Warning: No position data loaded from file: " << filePath << std::endl;
    }
    
    return positions;
}

void NodeManager::CreateNodes() {
    NS_LOG_FUNCTION(this);
    
    // 添加详细日志
    NS_LOG_INFO("Creating nodes based on loaded data");
    NS_LOG_INFO("Vehicle data entries: " << m_vehicleTrajectories.size());
    NS_LOG_INFO("Satellite data entries: " << m_satellitePositions.size());
    NS_LOG_INFO("Ground station data entries: " << m_groundStationPositions.size());
    
    // 创建车辆节点 - 数量由轨迹文件数量决定
    m_vehicleNodes.Create(m_vehicleTrajectories.size());
    
    // 创建卫星节点
    m_satelliteNodes.Create(m_satellitePositions.size());
    
    // 创建地面站节点
    m_groundStationNodes.Create(m_groundStationPositions.size());
    
    // 合并所有节点
    m_allNodes.Add(m_vehicleNodes);
    m_allNodes.Add(m_satelliteNodes);
    m_allNodes.Add(m_groundStationNodes);
    
    // 记录节点类型
    for (uint32_t i = 0; i < m_vehicleNodes.GetN(); i++) {
        m_nodeTypes[m_vehicleNodes.Get(i)->GetId()] = VEHICLE;
    }
    
    for (uint32_t i = 0; i < m_satelliteNodes.GetN(); i++) {
        m_nodeTypes[m_satelliteNodes.Get(i)->GetId()] = SATELLITE;
    }
    
    for (uint32_t i = 0; i < m_groundStationNodes.GetN(); i++) {
        m_nodeTypes[m_groundStationNodes.Get(i)->GetId()] = GROUND_STATION;
    }
    
    // 设置移动模型
    SetupVehicleMobility();
    SetupSatelliteMobility();
    SetupGroundStationMobility();
    
    // 设置传播模型
    SetupPropagationModels();
    
    // 在创建节点后添加日志
    NS_LOG_INFO("Created " << m_vehicleNodes.GetN() << " vehicle nodes");
    NS_LOG_INFO("Created " << m_satelliteNodes.GetN() << " satellite nodes");
    NS_LOG_INFO("Created " << m_groundStationNodes.GetN() << " ground station nodes");
    
    // 列出前几个车辆ID作为示例
    if (!m_vehicleNodes.GetN()) {
        NS_LOG_WARN("No vehicle nodes were created!");
    } else {
        std::string sampleVehicleIds = "Sample vehicle IDs: ";
        for (uint32_t i = 0; i < std::min(m_vehicleNodes.GetN(), (uint32_t)5); i++) {
            sampleVehicleIds += m_nodeToVehicleId[m_vehicleNodes.Get(i)->GetId()] + " ";
        }
        NS_LOG_INFO(sampleVehicleIds);
    }
}

void NodeManager::SetupVehicleMobility() {
    NS_LOG_FUNCTION(this);
    
    // 为每个车辆设置路径点移动模型
    uint32_t nodeIndex = 0;
    for (const auto& [vehicleId, trajectory] : m_vehicleTrajectories) {
        if (nodeIndex >= m_vehicleNodes.GetN()) {
            NS_LOG_ERROR("Not enough nodes created for all vehicle trajectories");
            break;
        }
        
        // 创建路径点列表
        Ptr<WaypointMobilityModel> mobility = CreateObject<WaypointMobilityModel>();
        
        for (const auto& point : trajectory) {
            Waypoint waypoint(Seconds(point.time), 
                             Vector(point.x, point.y, 0.0));
            mobility->AddWaypoint(waypoint);
        }
        
        // 安装到节点
        m_vehicleNodes.Get(nodeIndex)->AggregateObject(mobility);
        
        // 记录节点ID和车辆ID的映射关系
        m_nodeToVehicleId[m_vehicleNodes.Get(nodeIndex)->GetId()] = vehicleId;
        
        nodeIndex++;
    }
}

void NodeManager::SetupSatelliteMobility() {
    NS_LOG_FUNCTION(this);
    
    // 为卫星设置固定位置模型
    for (uint32_t i = 0; i < m_satelliteNodes.GetN(); i++) {
        Ptr<ConstantPositionMobilityModel> mobility = CreateObject<ConstantPositionMobilityModel>();
        mobility->SetPosition(Vector(
            m_satellitePositions[i].x,
            m_satellitePositions[i].y,
            m_satellitePositions[i].z
        ));
        m_satelliteNodes.Get(i)->AggregateObject(mobility);
    }
}

void NodeManager::SetupGroundStationMobility() {
    NS_LOG_FUNCTION(this);
    
    if (m_groundStationNodes.GetN() == 0) {
        NS_LOG_WARN("No ground station nodes to set up mobility");
        return;
    }
    
    // 配置地面站的移动模型(固定位置)
    for (uint32_t i = 0; i < m_groundStationNodes.GetN(); i++) {
        // 获取地面站位置
        double x = 0.0, y = 0.0, z = 0.0;
        
        if (i < m_groundStationPositions.size()) {
            x = m_groundStationPositions[i].x;
            y = m_groundStationPositions[i].y; // 确保正确使用y坐标
            z = m_groundStationPositions[i].z;
        }
        
        // 创建固定位置移动模型
        Ptr<ConstantPositionMobilityModel> mobility = CreateObject<ConstantPositionMobilityModel>();
        mobility->SetPosition(Vector(x, y, z));
        
        // 输出详细的地面站位置信息
        std::cout << "创建地面站 #" << i << " (节点ID: " << m_groundStationNodes.Get(i)->GetId() 
                 << "): 位置 [x=" << x << ", y=" << y << ", z=" << z << "]" << std::endl;
        
        // 同时记录到NS3日志
        NS_LOG_INFO("Ground station #" << i << " (Node ID: " << m_groundStationNodes.Get(i)->GetId()
                  << "): Position [x=" << x << ", y=" << y << ", z=" << z << "]");
        
        // 安装移动模型到节点
        m_groundStationNodes.Get(i)->AggregateObject(mobility);
        
        // 记录节点类型
        m_nodeTypes[m_groundStationNodes.Get(i)->GetId()] = GROUND_STATION;
    }
    
    NS_LOG_INFO("Ground station mobility setup completed");
}

void NodeManager::InstallInternetStack() {
    NS_LOG_FUNCTION(this);
    InternetStackHelper internet;
    internet.Install(m_allNodes);
    
    // 配置IP地址
    Ipv4AddressHelper ipv4;
    
    // 创建设备容器
    NetDeviceContainer vehicleDevices;
    NetDeviceContainer satelliteDevices;
    NetDeviceContainer groundStationDevices;
    
    // 此处应该创建和配置物理层设备 (例如通过PointToPointHelper等)
    // 示例: PointToPointHelper p2p; vehicleDevices = p2p.Install(m_vehicleNodes);
    
    // 为车辆分配IP地址 - 使用/16子网可以容纳65536个地址
    ipv4.SetBase("10.1.0.0", "255.255.0.0");
    Ipv4InterfaceContainer vehicleInterfaces = ipv4.Assign(vehicleDevices);
    NS_LOG_INFO("Assigned IP addresses to " << m_vehicleNodes.GetN() << " vehicle nodes");
    
    // 为卫星分配IP地址
    ipv4.SetBase("10.2.0.0", "255.255.0.0");
    Ipv4InterfaceContainer satelliteInterfaces = ipv4.Assign(satelliteDevices);
    NS_LOG_INFO("Assigned IP addresses to " << m_satelliteNodes.GetN() << " satellite nodes");
    
    // 为地面站分配IP地址
    ipv4.SetBase("10.3.0.0", "255.255.0.0");
    Ipv4InterfaceContainer groundStationInterfaces = ipv4.Assign(groundStationDevices);
    NS_LOG_INFO("Assigned IP addresses to " << m_groundStationNodes.GetN() << " ground station nodes");
}

void NodeManager::InstallApplications() {
    NS_LOG_FUNCTION(this);
    // 这里可以安装一些基本的应用来生成网络流量
    // 例如：在部分节点之间设置UDP Echo服务器和客户端
    
    // 实际应用将取决于具体的仿真需求
    // 这里只是一个简单的示例
    
    UdpEchoServerHelper echoServer(9);
    
    // 在一些地面站上安装UDP Echo服务器
    ApplicationContainer serverApps;
    for (uint32_t i = 0; i < m_groundStationNodes.GetN(); i++) {
        serverApps.Add(echoServer.Install(m_groundStationNodes.Get(i)));
    }
    serverApps.Start(Seconds(1.0));
    serverApps.Stop(Seconds(100.0));
    
    // 在车辆上安装UDP Echo客户端
    UdpEchoClientHelper echoClient(Ipv4Address("10.1.3.1"), 9);
    echoClient.SetAttribute("MaxPackets", UintegerValue(1000));
    echoClient.SetAttribute("Interval", TimeValue(Seconds(0.1)));
    echoClient.SetAttribute("PacketSize", UintegerValue(1024));
    
    ApplicationContainer clientApps;
    for (uint32_t i = 0; i < m_vehicleNodes.GetN(); i += 5) {  // 每5个车辆安装一个客户端
        if (i < m_vehicleNodes.GetN()) {
            clientApps.Add(echoClient.Install(m_vehicleNodes.Get(i)));
        }
    }
    clientApps.Start(Seconds(2.0));
    clientApps.Stop(Seconds(99.0));
}

NodeContainer NodeManager::GetAllNodes() const {
    return m_allNodes;
}

NodeContainer NodeManager::GetVehicleNodes() const {
    return m_vehicleNodes;
}

NodeContainer NodeManager::GetSatelliteNodes() const {
    return m_satelliteNodes;
}

NodeContainer NodeManager::GetGroundStationNodes() const {
    return m_groundStationNodes;
}

double NodeManager::GetDistance(uint32_t node1Id, uint32_t node2Id) const {
    Ptr<Node> node1 = nullptr;
    Ptr<Node> node2 = nullptr;
    
    // 查找节点
    for (uint32_t i = 0; i < m_allNodes.GetN(); i++) {
        if (m_allNodes.Get(i)->GetId() == node1Id) {
            node1 = m_allNodes.Get(i);
        }
        if (m_allNodes.Get(i)->GetId() == node2Id) {
            node2 = m_allNodes.Get(i);
        }
    }
    
    if (!node1 || !node2) {
        NS_LOG_ERROR("Node not found");
        return -1.0;
    }
    
    // 获取位置
    Ptr<MobilityModel> mobility1 = node1->GetObject<MobilityModel>();
    Ptr<MobilityModel> mobility2 = node2->GetObject<MobilityModel>();
    
    if (!mobility1 || !mobility2) {
        NS_LOG_ERROR("Mobility model not found");
        return -1.0;
    }
    
    // 计算距离
    return mobility1->GetDistanceFrom(mobility2);
}

NodeType NodeManager::GetNodeType(uint32_t nodeId) const {
    auto it = m_nodeTypes.find(nodeId);
    if (it != m_nodeTypes.end()) {
        return it->second;
    }
    
    NS_LOG_ERROR("Node type not found for node ID: " << nodeId);
    return VEHICLE; // 默认返回车辆类型
}

std::vector<VehicleData> NodeManager::GetVehicleDataAtTime(double time) const {
    std::vector<VehicleData> result;
    
    // 对每个车辆，找到最接近指定时间的位置
    for (const auto& [vehicleId, trajectory] : m_vehicleTrajectories) {
        // 查找最接近time的数据点
        auto it = std::lower_bound(
            trajectory.begin(), 
            trajectory.end(), 
            time,
            [](const VehicleData& data, double t) {
                return data.time < t;
            }
        );
        
        // 如果找到了点
        if (it != trajectory.end()) {
            // 如果不是第一个点且当前点的时间大于目标时间，考虑使用前一个点
            if (it != trajectory.begin() && std::abs((it-1)->time - time) < std::abs(it->time - time)) {
                it--;
            }
            
            // 添加到结果中
            if (std::abs(it->time - time) < 0.5) { // 允许0.5秒的误差
                result.push_back(*it);
            }
        }
    }
    
    // 添加日志，显示当前时间点有多少活跃车辆
    NS_LOG_INFO("Found " << result.size() << " active vehicles at time " << time);
    
    return result;
}

void NodeManager::SetGroundStationCoverageRadius(double radius)
{
    NS_LOG_FUNCTION(this << radius);
    m_groundStationCoverageRadius = radius;
    
    if (m_groundStationPropagationModel) {
        DynamicCast<GroundStationPropagationLossModel>(m_groundStationPropagationModel)->SetCoverageRadius(radius);
    }
}

void NodeManager::SetSatelliteMaxElevationAngle(double angle)
{
    NS_LOG_FUNCTION(this << angle);
    m_satelliteMaxElevationAngle = angle;
    
    if (m_satellitePropagationModel) {
        DynamicCast<SatellitePropagationLossModel>(m_satellitePropagationModel)->SetMaximumElevationAngle(angle);
    }
}

void NodeManager::SetupPropagationModels()
{
    NS_LOG_FUNCTION(this);
    
    // 创建地面站传播模型
    m_groundStationPropagationModel = PropagationModelFactory::CreateGroundStationPropagationModel(m_groundStationCoverageRadius);
    
    // 创建卫星传播模型
    m_satellitePropagationModel = PropagationModelFactory::CreateSatellitePropagationModel(m_satelliteMaxElevationAngle);
    
    NS_LOG_INFO("Propagation models set up: Ground station coverage radius = " 
                << m_groundStationCoverageRadius << "m, Satellite max elevation angle = " 
                << m_satelliteMaxElevationAngle << " degrees");
}

double NodeManager::CalculateGroundStationSINR(uint32_t vehicleNodeId, uint32_t stationNodeId) const
{
    NS_LOG_FUNCTION(this << vehicleNodeId << stationNodeId);
    
    Ptr<Node> vehicleNode = nullptr;
    Ptr<Node> stationNode = nullptr;
    
    // 查找节点
    for (uint32_t i = 0; i < m_vehicleNodes.GetN(); i++) {
        if (m_vehicleNodes.Get(i)->GetId() == vehicleNodeId) {
            vehicleNode = m_vehicleNodes.Get(i);
            break;
        }
    }
    
    for (uint32_t i = 0; i < m_groundStationNodes.GetN(); i++) {
        if (m_groundStationNodes.Get(i)->GetId() == stationNodeId) {
            stationNode = m_groundStationNodes.Get(i);
            break;
        }
    }
    
    if (!vehicleNode || !stationNode) {
        NS_LOG_ERROR("Node not found");
        return -100.0;
    }
    
    // 获取移动模型
    Ptr<MobilityModel> vehicleMobility = vehicleNode->GetObject<MobilityModel>();
    Ptr<MobilityModel> stationMobility = stationNode->GetObject<MobilityModel>();
    
    if (!vehicleMobility || !stationMobility) {
        NS_LOG_ERROR("Mobility model not found");
        return -100.0;
    }
    
    // 发送功率 (dBm)
    double txPower = 20.0;
    
    // 计算接收功率
    double rxPower = m_groundStationPropagationModel->CalcRxPower(txPower, stationMobility, vehicleMobility);
    
    // 噪声功率 (dBm)
    double noisePower = -90.0;
    
    // 干扰功率 (简化，假设干扰为噪声的一小部分)
    double interference = -100.0;
    
    // 计算SINR
    double sinr = rxPower - (noisePower + interference);
    
    return sinr;
}

double NodeManager::CalculateSatelliteSINR(uint32_t vehicleNodeId, uint32_t satelliteNodeId) const
{
    NS_LOG_FUNCTION(this << vehicleNodeId << satelliteNodeId);
    
    Ptr<Node> vehicleNode = nullptr;
    Ptr<Node> satelliteNode = nullptr;
    
    // 查找节点
    for (uint32_t i = 0; i < m_vehicleNodes.GetN(); i++) {
        if (m_vehicleNodes.Get(i)->GetId() == vehicleNodeId) {
            vehicleNode = m_vehicleNodes.Get(i);
            break;
        }
    }
    
    for (uint32_t i = 0; i < m_satelliteNodes.GetN(); i++) {
        if (m_satelliteNodes.Get(i)->GetId() == satelliteNodeId) {
            satelliteNode = m_satelliteNodes.Get(i);
            break;
        }
    }
    
    if (!vehicleNode || !satelliteNode) {
        NS_LOG_ERROR("Node not found");
        return -100.0;
    }
    
    // 获取移动模型
    Ptr<MobilityModel> vehicleMobility = vehicleNode->GetObject<MobilityModel>();
    Ptr<MobilityModel> satelliteMobility = satelliteNode->GetObject<MobilityModel>();
    
    if (!vehicleMobility || !satelliteMobility) {
        NS_LOG_ERROR("Mobility model not found");
        return -100.0;
    }
    
    // 发送功率 (dBm) - 卫星发送功率通常较高
    double txPower = 30.0;
    
    // 计算接收功率
    double rxPower = m_satellitePropagationModel->CalcRxPower(txPower, satelliteMobility, vehicleMobility);
    
    // 噪声功率 (dBm)
    double noisePower = -90.0;
    
    // 干扰功率 (简化，假设干扰为噪声的一小部分)
    double interference = -100.0;
    
    // 计算SINR
    double sinr = rxPower - (noisePower + interference);
    
    return sinr;
}

double NodeManager::GetGroundStationLoad(uint32_t stationNodeId) const
{
    auto it = m_nodeLoads.find(stationNodeId);
    if (it != m_nodeLoads.end()) {
        // 返回标准化的负载 (0-1)
        return static_cast<double>(it->second) / 20.0; // 假设每个基站最多服务20个车辆
    }
    return 0.0;
}

double NodeManager::GetSatelliteLoad(uint32_t satelliteNodeId) const
{
    auto it = m_nodeLoads.find(satelliteNodeId);
    if (it != m_nodeLoads.end()) {
        // 返回标准化的负载 (0-1)
        return static_cast<double>(it->second) / 50.0; // 假设每个卫星最多服务50个车辆
    }
    return 0.0;
}

std::string NodeManager::GetVehicleIdForNode(uint32_t nodeId) const
{
    auto it = m_nodeToVehicleId.find(nodeId);
    if (it != m_nodeToVehicleId.end()) {
        return it->second;
    }
    return ""; // 如果没找到，返回空字符串
}

void NodeManager::AddGroundStations(const std::string& positionFile, uint32_t count)
{
    NS_LOG_FUNCTION(this << positionFile << count);
    
    // 确保位置文件存在
    std::ifstream file(positionFile.c_str());
    if (!file.is_open()) {
        NS_LOG_ERROR("无法打开地面站位置文件: " << positionFile);
        return;
    }
    
    // 创建节点
    m_groundStationNodes.Create(count);
    
    // 打印文件内容以验证
    std::cout << "-----开始读取地面站文件-----" << std::endl;
    std::cout << "文件路径: " << positionFile << std::endl;
    
    // 读取CSV文件标题行
    std::string headerLine;
    std::getline(file, headerLine);
    std::cout << "CSV标题行: " << headerLine << std::endl;
    
    // 准备存储地面站位置信息
    m_groundStationPositions.clear();
    std::vector<Vector> positions;
    uint32_t stationCount = 0;
    
    // 重置文件指针，准备逐行读取
    file.clear();
    file.seekg(0, std::ios::beg);
    std::getline(file, headerLine); // 再次跳过标题行
    
    // 逐行读取地面站位置信息
    std::string line;
    while (std::getline(file, line) && stationCount < count) {
        std::cout << "原始CSV行: " << line << std::endl;
        
        std::istringstream ss(line);
        double x = 0.0, y = 0.0, z = 0.0;
        std::string token;
        
        // 解析X坐标
        if (std::getline(ss, token, ',')) {
            try {
                x = std::stod(token);
            } catch (const std::exception& e) {
                std::cout << "错误: 无法解析X坐标 '" << token << "': " << e.what() << std::endl;
                continue;
            }
        } else {
            std::cout << "错误: CSV行格式不正确，无法读取X坐标" << std::endl;
            continue;
        }
        
        // 解析Y坐标
        if (std::getline(ss, token, ',')) {
            try {
                y = std::stod(token);
                std::cout << "成功读取Y坐标: " << y << std::endl;
            } catch (const std::exception& e) {
                std::cout << "错误: 无法解析Y坐标 '" << token << "': " << e.what() << std::endl;
                continue;
            }
        } else {
            std::cout << "错误: CSV行格式不正确，无法读取Y坐标" << std::endl;
            continue;
        }
        
        // 解析Z坐标
        if (std::getline(ss, token, ',')) {
            try {
                z = std::stod(token);
            } catch (const std::exception& e) {
                std::cout << "警告: 无法解析Z坐标 '" << token << "': " << e.what() << std::endl;
                z = 0.0; // 使用默认值
            }
        } else {
            z = 0.0; // 如果没有Z值，使用默认值
        }
        
        // 保存位置数据到两个地方：positions数组和m_groundStationPositions
        Vector position(x, y, z);
        positions.push_back(position);
        
        PositionData posData;
        posData.id = std::to_string(stationCount);
        posData.x = x;
        posData.y = y;
        posData.z = z;
        m_groundStationPositions.push_back(posData);
        
        std::cout << "地面站 #" << stationCount << " 位置数据: (" << x << ", " << y << ", " << z << ")" << std::endl;
        stationCount++;
    }
    
    file.close();
    
    if (positions.empty()) {
        NS_LOG_ERROR("没有从文件中读取到有效的地面站位置数据");
        return;
    }
    
    // 为每个节点设置位置
    for (uint32_t i = 0; i < std::min(stationCount, count); i++) {
        if (i < positions.size()) {
            // 创建移动模型
            Ptr<ConstantPositionMobilityModel> mobility = CreateObject<ConstantPositionMobilityModel>();
            Vector position = positions[i];
            
            // 输出位置信息
            std::cout << "正在设置地面站 #" << i << " 的位置为: (" 
                     << position.x << ", " << position.y << ", " << position.z << ")" << std::endl;
            
            // 设置位置
            mobility->SetPosition(position);
            
            // 将移动模型安装到节点
            Ptr<Node> node = m_groundStationNodes.Get(i);
            node->AggregateObject(mobility);
            
            // 设置节点类型
            m_nodeTypes[node->GetId()] = GROUND_STATION;
            
            // 将节点添加到全局节点列表
            m_allNodes.Add(node);
            
            // 验证位置设置是否成功
            Ptr<MobilityModel> installedMobility = node->GetObject<MobilityModel>();
            if (installedMobility) {
                Vector pos = installedMobility->GetPosition();
                std::cout << "地面站 #" << i << " 实际安装的位置: (" 
                          << pos.x << ", " << pos.y << ", " << pos.z << ")" << std::endl;
                
                // 检查坐标是否正确设置
                if (std::abs(pos.x - position.x) > 1e-6 || 
                    std::abs(pos.y - position.y) > 1e-6 || 
                    std::abs(pos.z - position.z) > 1e-6) {
                    std::cout << "警告: 地面站 #" << i << " 位置设置不正确！" << std::endl;
                    std::cout << "  期望值: (" << position.x << ", " << position.y << ", " << position.z << ")" << std::endl;
                    std::cout << "  实际值: (" << pos.x << ", " << pos.y << ", " << pos.z << ")" << std::endl;
                }
            } else {
                std::cout << "错误: 地面站 #" << i << " 移动模型安装失败" << std::endl;
            }
        }
    }
    
    std::cout << "成功添加 " << stationCount << " 个地面站" << std::endl;
    std::cout << "-----地面站设置完成-----" << std::endl;
    NS_LOG_INFO("成功添加 " << stationCount << " 个地面站");
}



} // namespace ns3
